<?php

/**
 * Manage_productsController - Controller dùng để quản lý tin tức
 * 
 * @author huytbt
 * @date 2011-06-30
 * @version 1.0
 */
class Manage_productsController extends Controller
{
	//public $backend_left_menu_datas = false;
	private $_model;
	public $layout='//layouts/main';
	public $categoryTitle=false;
	public $pageTitle="Manage products";

	public function init()
	{
			Yii::app()->theme = 'backend';
			parent::init();
	}
    /**
     * @todo Kiểm tra quyền
     */
    /**
     * @return string Trả về các action (cách nhau bằng dấu phẩy) cho phép truy cập mà không cần xác thực quyền
    public function allowedActions() {
        return '*';
    }
     */

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */

    public function actionView($id)
    {
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'View a product';
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets/products');
		Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/manifest.css');
		Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/products.css');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.ui.widget.min.js');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.marcopolo.min.js');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.manifest.min.js');
		
        $model = new Products;
        $modelMiddle = new ProductMiddle;
        $modelCategories = ProductCategories::model()->findAll();
        
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $catIdsBelongTo = array();
        if (isset($_POST['Products'])) {
            $model->attributes = $_POST['Products'];
			$styles = "";
			foreach ($_POST['Products']['itemStyle'] as $item) {
				$styles .= $item."; ";
			}
			$model->style = $styles;
            $model->validate();
           	$modelMiddle->attributes = $_POST['ProductMiddle'];
        	if(empty($_POST['ProductMiddle']['category_id'])){
        		$model->addError('categories', 'Chưa xác định danh mục sản phẩm.');
        	}else{
        		$catIdsBelongTo = $_POST['ProductMiddle']['category_id'];
        	}
			//CVarDumper::dump($model->getErrors(), 5, true);	exit;
        	if(!$model->hasErrors()){
            	$fileUpload = CUploadedFile::getInstance($model, 'image');
            	if (isset($fileUpload)) {
            		$uploadPath = YiiBase::getPathOfAlias('webroot') . $this->module->image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
            	
            		if (!is_dir($uploadPath))
            			mkdir($uploadPath,0777,true);
            	
            		$filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
            		$fileUpload->saveAs($uploadPath . $filename);
            		
            		// thumbnails image
            		$thumbsPath = $uploadPath;
            		Yii::import('ext.phpthumb.EasyPhpThumb');
            		$thumbs = new EasyPhpThumb();
            		$thumbs->init();
            		$thumbs->setThumbsDirectory($thumbsPath);
            		$thumbs->load($uploadPath . $filename)
            		->resize(Yii::app()->controller->module->image['lager']['width'], 
            				 Yii::app()->controller->module->image['lager']['height'])
            		->save('thumb_'.$filename);
            	
            		$model->image = $filename;
            	}
            		
				$catalogFileUpload = CUploadedFile::getInstance($model, 'catalog_image');
            	if (isset($catalogFileUpload)) {
            		$uploadCatalogPath = YiiBase::getPathOfAlias('webroot') . $this->module->catalog_image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
            	
            		if (!is_dir($uploadCatalogPath))
            			mkdir($uploadCatalogPath,0777,true);
            	
            		$filename = $model->alias . 'Catalog.' . $catalogFileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $catalogFileUpload->getExtensionName();
            		$catalogFileUpload->saveAs($uploadCatalogPath . $filename);
            		
            		// thumbnails image
            		$thumbsPath = $uploadCatalogPath;
            		Yii::import('ext.phpthumb.EasyPhpThumb');
            		$thumbs = new EasyPhpThumb();
            		$thumbs->init();
            		$thumbs->setThumbsDirectory($thumbsPath);
            		$thumbs->load($uploadCatalogPath . $filename)
            		->resize(Yii::app()->controller->module->catalog_image['lager']['width'], 
            				 Yii::app()->controller->module->catalog_image['lager']['height'])
            		->save('thumb_'.$filename);
            	
            		$model->catalog_image = $filename;
            	}
            	
            	$modelMiddle->validate();
            	$transaction=$model->dbConnection->beginTransaction();
            	try {
            		//$model->created = time();
            		//$model->modified = time();
            		$model->product_date = $model->n_date . '|' . $model->n_hours . '|' . $model->n_minutes;
            		if ($model->save() && is_array($modelMiddle->category_id)) {
            			foreach ($modelMiddle->category_id as $cat) {
            				$middle = new ProductMiddle;
            				$middle->category_id = $cat;
            				$middle->product_id = $model->id;
            				if (!$middle->save())
            					throw new Exception('Can not create product');
            			}
            	
            			$transaction->commit();
            			//$this->redirect(array('view', 'id' => $model->id));
            			$this->redirect(array('admin'));
            			echo '<script>parent.location=parent.location;</script>';
            			//Yii::app()->end();
            			$this->redirect(array('admin'));
            		} else
            			throw new Exception('Can not create product');
            	} catch (Exception $e){
            		$transaction->rollBack();
            	}
            }
        } else {
			$model->is_published = 1;
		}

        if (empty($model->n_date)) {
            $model->n_date = date('m/d/Y', time());
            $model->n_hours = date('h', time());
            $model->n_minutes = date('i', time());
        }
		
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'Create a product';
        $this->render('create', array(
            'model' => $model,
            'modelCategories' => $modelCategories,
        	'catIdsBelongTo'=>$catIdsBelongTo,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets/products');
		//Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/style.css');
		Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/products.css');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.ui.widget.min.js');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.marcopolo.min.js');
		Yii::app()->getClientScript()->registerScriptFile($baseScriptUrl.'/js/jquery.manifest.min.js');
		
        $model = $this->loadModel($id);
        
        $modelCategories = ProductCategories::model()->findAll();
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $catIdsBelongTo = array();
        if (isset($_POST['Products'])) {
        	$model->attributes = $_POST['Products'];
			$styles = "";
			if (count($_POST['Products']['itemStyle'])) {
				$countItem = 0;
				foreach ($_POST['Products']['itemStyle'] as $item) {
					if($item != "") {
						$styles .= $item;
						if($countItem || !substr_count($styles, ";"))
							$styles .= "; ";
					}
					$countItem++;
				}
			}
			$model->style = $styles;
        	$model->validate();
	        if(empty($_POST['ProductMiddle']['category_id'])){
	        	$model->addError('categories', 'Chưa xác định danh mục tin tức.');
	        }else{
        		$catIdsBelongTo = $productCatIds = $_POST['ProductMiddle']['category_id'];
	        }
        		
	        if(!$model->hasErrors()){
        		$fileUpload = CUploadedFile::getInstance($model, 'image');
        		if (isset($fileUpload)) {
        			$uploadPath = YiiBase::getPathOfAlias('webroot') . $this->module->image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
        		
        			// Delete old image
        			if ($model->image) {
        				if(is_file($uploadPath . '/' . $model->image))
        					unlink($uploadPath . '/' . $model->image);
        			}
        		
        			if (!is_dir($uploadPath))
        				mkdir($uploadPath,777,true);
        		
        			$filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
        			$fileUpload->saveAs($uploadPath . '/' . $filename);
        			
        			// thumbnails image
        			$thumbsPath = $uploadPath;
        			Yii::import('ext.phpthumb.EasyPhpThumb');
        			$thumbs = new EasyPhpThumb();
        			$thumbs->init();
        			$thumbs->setThumbsDirectory($thumbsPath);
        			$thumbs->load($uploadPath . '/' . $filename)
						->resize(Yii::app()->controller->module->image['lager']['width'], 
            				 Yii::app()->controller->module->image['lager']['height'])
        				->save('thumb_'.$filename);
        			$model->image = $filename;
        		}
				
        		$fileCatalogUpload = CUploadedFile::getInstance($model, 'catalog_image');
        		if (isset($fileCatalogUpload)) {
        			$uploadCatalogPath = YiiBase::getPathOfAlias('webroot') . $this->module->catalog_image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
        			// Delete old catalog_image
        			if ($model->catalog_image) {
        				if(is_file($uploadCatalogPath . '/' . $model->catalog_image))
        					unlink($uploadCatalogPath . '/' . $model->catalog_image);
        			}
        			if (!is_dir($uploadCatalogPath))
        				mkdir($uploadCatalogPath,777,true);
        			$filename = $model->alias . 'Catalog.' . $fileCatalogUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileCatalogUpload->getExtensionName();
        			$fileCatalogUpload->saveAs($uploadCatalogPath . '/' . $filename);
        			
        			// thumbnails catalog_image
        			$thumbsPath = $uploadCatalogPath;
        			Yii::import('ext.phpthumb.EasyPhpThumb');
        			$thumbs = new EasyPhpThumb();
        			$thumbs->init();
        			$thumbs->setThumbsDirectory($thumbsPath);
        			$thumbs->load($uploadCatalogPath . '/' . $filename)
						->resize(Yii::app()->controller->module->catalog_image['lager']['width'], 
            				 Yii::app()->controller->module->catalog_image['lager']['height'])
        				->save('thumb_'.$filename);
        		
        			$model->catalog_image = $filename;
        		}
        		
        		$model->modified = time();
        		$transaction=$model->dbConnection->beginTransaction();
        		try{
        			$model->save();
        			 
        			$ProductMiddle = ProductMiddle::model();
        			$ProductMiddle->deleteAll('product_id=:id',array(':id'=>$model->id));
        			 
        			foreach ($productCatIds as $catId){
        				$ProductMiddle = new ProductMiddle;
        				$ProductMiddle->attributes = array('product_id'=>$model->id,'category_id'=>$catId);
        				$ProductMiddle->save(true);
        			}
        			 
        			$transaction->commit();
        		}catch(Exception $err){
        			$transaction->rollback();
        		}
        	}
        }else{
        	$catsBelongTo = ProductMiddle::model()->findAll('product_id=:id',array(':id'=>$model->id));
	        $catIdsBelongTo = array();
	        foreach ($catsBelongTo as $row){
	        	$catIdsBelongTo[] = $row->category_id;
	        }
        }
        
        if (empty($model->n_date)) {
            $arrProductDay = explode('|', $model->product_date);
            $model->n_date = $arrProductDay[0];
            $model->n_hours = $arrProductDay[1];
            $model->n_minutes = $arrProductDay[2];
        }
        
		$this->categoryTitle = $this->pageTitle;
		$this->pageTitle = 'Edit a product';
        $this->render('update', array(
            'model' => $model,
            'modelCategories' => $modelCategories,
        	'catIdsBelongTo' => $catIdsBelongTo,
        ));
    }
    
    public function actionAjaxupdate($id){
    	$model = $this->loadModel($id);
    	if (isset($_POST['Products'])){
    		$model->attributes = $_POST['Products'];
    		$model->save(true);
    		print_r($_POST['Products']);
    	}
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            if ($model->image) {
                $uploadPath = YiiBase::getPathOfAlias('webroot') . $this->module->image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
                if(is_file($uploadPath . '/' . $model->image))
                	unlink($uploadPath . '/' . $model->image);
            }
            if ($model->catalog_image) {
                $uploadPath = YiiBase::getPathOfAlias('webroot') . $this->module->catalog_image['url']; //Yii::app()->basePath . '/../jlwebroot/upload';
                if(is_file($uploadPath . '/' . $model->catalog_image))
                	unlink($uploadPath . '/' . $model->catalog_image);
            }
            $model->delete();
            
            $middle = ProductMiddle::model()->deleteAllByAttributes(array('product_id'=>$id));

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        if (isset($_POST['product-entries-grid_c0']))
        {
            foreach ($_POST['product-entries-grid_c0'] as $strNewID) {
                $model = $this->loadModel($strNewID);
                $model->delete();
            }
        }
        
        $model = new Products('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Products']))
            $model->attributes = $_GET['Products'];
        $this->render('admin', array(
            'model' => $model,
			'pageTitle' => 'Manage products'
        ));
    }
		
		

    /**
     * Manages product in a categories.
     */
    public function actionProductCategory($alias = null)
    {
        if (isset($_POST['product-entries-grid_c0']))
        {
            foreach ($_POST['product-entries-grid_c0'] as $strProductID) {
                $model = $this->loadModel($strProductID);
                $model->delete();
            }
        }
        $model = new Products('category_search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Products']))
            $model->attributes = $_GET['Products'];
        $this->render('product_category', array(
            'model' => $model,
						'alias'	=>	$alias
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Products::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-entries-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionUpload(){
    	Yii::import('ext.ckeditor.CkEditorUploader');
    	$config = array(
    			'url'=>$this->module->image['url'],//'/wwwroot/upload_files/product/',
    	);
    	CkEditorUploader::$config = $config;
    	CkEditorUploader::upload();
    }
}
